<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">主题名称</label>
        <el-input v-model="query.themeName" clearable placeholder="主题名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">所属分类</label>
        <el-input v-model="query.typeId" clearable placeholder="所属分类" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">

        <template v-slot:right>
          <el-upload
            accept=".xlsx, .xls, .csv"
            :file-list="fileList"
            :action="actionUrl"
            :data="info"
            :before-upload="beforeUploadFile"
            :on-exceed="exceedFile"
            :on-success="uploadSuccess"
            :show-file-list="isShowFile"
            :headers="headers"
            multiple
            class="filter-item"
            :limit="limitNum"
          >
            <el-button
              v-if="crud.optShow.download"
              :loading="crud.downloadLoading"
              :disabled="crud.selections.length !== 1"
              type="success"
              icon="el-icon-edit"
              size="mini"
            >上传</el-button>
          </el-upload>
        </template>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="主题名称" prop="themeName">
            <el-input v-model="form.themeName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="所属分类" prop="typeId">
            <el-select v-model="form.typeId" filterable placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="typeId" label="所属分类" />
        <el-table-column prop="themeName" label="主题名称" />
        <el-table-column v-if="checkPer(['admin','zhTheme:edit','zhTheme:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudZhTheme from '@/api/zhTheme'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getTypeDict } from '@/api/zhType'
import { getToken } from '@/utils/auth'
const defaultForm = { id: null, themeName: null, isDeleted: null, typeId: null }
export default {
  name: 'ZhTheme',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['theme_type'],
  cruds() {
    return CRUD({ title: '主题管理', url: 'api/zhTheme', idField: 'id', sort: 'typeId,desc', crudMethod: { ...crudZhTheme }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'zhTheme:add'],
        edit: ['admin', 'zhTheme:edit'],
        del: ['admin', 'zhTheme:del']
      },
      rules: {
        themeName: [
          { required: true, message: '主题名称不能为空', trigger: 'blur' }
        ],
        typeId: [
          { required: true, message: '所属分类不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'themeName', display_name: '主题名称' },
        { key: 'typeId', display_name: '所属分类' }
      ],
      headers: {
        'Authorization': getToken()
      },
      typeOptions: [],
      actionUrl: '/api/zhihuQuestion/import',
      info: {
        themeId: ''
      },
      fileList: [],
      limitNum: 5,
      isShowFile: true
    }
  },
  created() {
    getTypeDict().then(data => {
      this.typeOptions = data
    })
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 文件上传之前的钩子
    beforeUploadFile(file) {
      const FileExt = file.name.replace(/.+\./, '')
      if (['xls', 'xlsx', 'csv'].indexOf(FileExt.toLowerCase()) === -1) {
        this.$message({
          type: 'warning',
          message: '请上传后缀名为xls、xlsx、csv的附件！'
        })
        return false
      }
    },
    // 文件超出个数时的钩子
    exceedFile(files, fileList) {
      console.log('文件超出个数：', files)
      this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length +
      fileList.length} 个`)
    },
    // 文件上传成功的钩子
    uploadSuccess(response, file, fileList) {
      if (response.code !== 200) {
        return this.$message.error(response.msg)
      } else {
        // 上传成功之后在这里写逻辑，比如：重新调用查询列表接口
        return this.$message.success(response.msg)
      }
    }
  }
}
</script>

<style scoped>

</style>
